# -*- coding: utf-8 -*-
import pymysql
from douban_movie.items import DoubanMovieReviewItem, DoubanMovieReviewDetailItem, DoubanMovieCommentItem
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

# 影评基本信息
class DoubanMovieReviewPipeline(object):
    def __init__(self):
        dbparam = {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "password": "root",
            "database": "douban"
        }
        self.conn = pymysql.connect(**dbparam)
        self.cursor = self.conn.cursor()
    def process_item(self, item, spider):
        if isinstance(item, DoubanMovieReviewItem):
            sql = """
            REPLACE INTO review (id, movie_id, avatar, nick, level, create_time, title, up, down, reply)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """
            self.cursor.execute(sql, list(item.values()))
            self.conn.commit()
        return item

    def __del__(self):
        self.cursor.close()
        self.conn.close()

# 影评内容
class DoubanMovieReviewDetailPipeline(object):
    def __init__(self):
        dbparam = {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "password": "root",
            "database": "douban"
        }
        self.conn = pymysql.connect(**dbparam)
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        if isinstance(item, DoubanMovieReviewDetailItem):
            sql = """
            REPLACE INTO review_detail (review_id, content)
            VALUES (%s, %s)
            """
            self.cursor.execute(sql, list(item.values()))
            self.conn.commit()
        return item

    def __del__(self):
        self.cursor.close()
        self.conn.close()

# 评论内容
class DoubanMovieCommentPipeline(object):
    def __init__(self):
        dbparam = {
            "host": "127.0.0.1",
            "port": 3306,
            "user": "root",
            "password": "root",
            "database": "douban"
        }
        self.conn = pymysql.connect(**dbparam)
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        if isinstance(item, DoubanMovieCommentItem):
            sql = """
            REPLACE INTO comment (id, movie_id, avatar, nick, level, vote, content)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
            """
            self.cursor.execute(sql, list(item.values()))
            self.conn.commit()
        return item

    def __del__(self):
        self.cursor.close()
        self.conn.close()